package org.simple.base.util

import org.nutz.http.Header
import org.nutz.http.Request
import org.nutz.http.Sender
import org.simple.base.json.util.JsonUtil
import org.simple.base.model.QuickMap

class JsonApiUtil {

    public static String POST_DATA = 'postData'

    public static String HEADER = 'HEADER'

    static QuickMap call(String api, Request.METHOD method, Map<String, Object> paramMap) {
        return call(api, paramMap, method, QuickMap)
    }

    static QuickMap call(String api, Request.METHOD method) {
        return call(api, null, method, QuickMap)
    }

    static <T> T call(String api, Request.METHOD method, Map<String, Object> paramMap, Class<T> responseClass) {
        return call(api, paramMap, method, responseClass)
    }

    static <T> T call(String api, Map<String, Object> paramMap, Class<T> responseClass = QuickMap) {
        return call(api, paramMap, Request.METHOD.POST, responseClass)
    }

    static <T> T call(String api, Map<String, Object> paramMap,
                      Request.METHOD method,
                      Class<T> responseClass,
                      Integer timeout = 0) {
        def r = paramMap ? Request.create(api, method, paramMap) : Request.create(api, method)

        Header header = (Header) paramMap?.get(HEADER)

        if (header) {
            r.header = header
            paramMap?.remove(HEADER)
        }

        String postData = JsonUtil.toJson(paramMap?.get(POST_DATA))
        if (postData) {
            r.setData(postData)
            paramMap?.remove(POST_DATA)
        }

        def sender = Sender.create(r)
        sender.timeout = timeout
        String json = sender.send().getContent()

        if (json) {
            return JsonUtil.fromJson(responseClass, json)
        }

        return null
    }
}